const video = document.getElementById('video');

//加载训练好的模型
Promise.all([
    faceapi.nets.tinyFaceDetector.loadFromUri('./models'),
    faceapi.nets.faceLandmark68Net.loadFromUri('./models'),//记录玛雅面孔的不同位置
    faceapi.nets.faceRecognitionNet.loadFromUri('./models'),//识别脸部周围
    faceapi.nets.faceExpressionNet.loadFromUri('./models'),//识别脸部表桥
]).then(startVideo);

function startVideo() {
    //如果想在服务器发布使用必须使用HTTPS否则无法调用摄像头
    //该对象可提供对相机和麦克风等媒体输入设备的连接访问，也包括屏幕共享
    navigator.mediaDevices.getUserMedia({
        audio: false,
        video: true
    }).then(stream => video.srcObject = stream)
        .catch(err => console.log(err));
}

video.addEventListener('play', () => {
    const canvas = faceapi.createCanvasFromMedia(video);
    document.body.appendChild(canvas);
    const displaySize = {width: video.width, height: video.height};
    faceapi.matchDimensions(canvas, displaySize);

    const cycleFunc = async () => {
        //链式调用
        const detections = await faceapi.detectAllFaces(video,
            new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions();

        const resizeDetections = faceapi.resizeResults(detections, displaySize);
        canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
        faceapi.draw.drawDetections(canvas, resizeDetections);
        faceapi.draw.drawFaceExpressions(canvas, resizeDetections);
        faceapi.draw.drawFaceLandmarks(canvas, resizeDetections);
        requestAnimationFrame(cycleFunc);
    };

    cycleFunc();
});